import React from 'react';
import {connect} from 'dva';
import PropTypes from 'prop-types';
import {Row,Col,Form, Icon, Input, Button, Checkbox,Radio,Modal,message} from 'antd';
import style from '../../styles/login.less';
import {numvail,selectvail} from '../../utils/Validator.js'
import reqwest from 'reqwest';
import {creat_account} from '../../models/Role.js'
import {reqwest_post,reqwest_get} from '../../utils/Reqwest.js'
const FormItem = Form.Item;
let _html = [
  {label:'手机',icon:<Icon type="mobile" style={{ fontSize: 14 }} />,id:'Cre_tel',help:'提交表单后会使用短信告知初始密码',rule:{rules: [{ required: true, message: '请输入正确的手机号码',validator:(rule,value,callback)=>{
    numvail(rule,value,callback)
  } }]}},
  {label:'姓名',icon:<Icon type="user" style={{ fontSize: 14 }} />,help:'',id:'CreUserName',rule:{
    rules: [{ required: true ,message:'请输入用户姓名'}],
  }}
]
class Account extends React.Component{
	constructor(props){
		super(props);
		this.state={
			userole:'saler',
      visible:false,
      // saler:[{"id":2,"name":"cs_director","mobile":"15802162349","role":"saler_director"},{"id":3,"name":"张晓","mobile":"15802162347","role":"saler_director"},{"id":4,"name":"张明","mobile":"15802162348","role":"saler_director"},{"id":8,"name":"潘海梅","mobile":"15168650222","role":"saler_director"}],
      saler:[],
      loading:false,
      salboss:undefined,
		}
	}
  handleModal(value){
    reqwest_get('/api/accounts/get_directors',{access_token:window.localStorage['token'],role:value},(data)=>{
      if(data.status=='success'){
        this.setState({
          saler:data.list,
          visible:true
        })
      }
    })
  }
  componentWillMount(){
    // reqwest_get('/api/accounts/get_saler_directors',{access_token:window.localStorage['token']},(data)=>{
    //   if(data.status=='success'){
    //     this.setState({
    //       saler:data.list
    //     })
    //   }
    // })
    // reqwest({
    //   url: window.host+'/api/accounts/get_saler_directors',
    //   method: 'get',
    //   crossOrigin: true,
    //   type: 'json',
    //   data:{access_token:window.localStorage['token']},
    //   // contentType: 'application/json',
    //   // headers:{
    //   //   'Access-Control-Allow-Origin':'*'
    //   // }
    // }).then((data) => {
    //   if(data.status=='success'){
    //     this.setState({
    //       saler:data.list
    //     })
    //   }
    // }).fail((err,msg)=>{
    //   console.log(err)
    // });
  }
  handleRadioChange(e){
    const {saler} = this.state;
    const {value} = e.target;
    console.log(e)
    switch(value){
      case 'saler':this.handleModal(value)
      break;
      case 'acct':this.handleModal(value)
      break;
      case 'cs':this.handleModal(value)
      break;
      case 'operator':this.handleModal(value)
      break;
    }

    // if(e.target.value=='saler'&&saler.length>0){
    //   this.setState({visible:true})
    // }
    this.setState({userole:e.target.value});
  }
  handleOk(){

    this.setState({visible:false});
      
  }
	handleSubmit(e){
    e.preventDefault();
    let _this=this;
    let _data=null;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
        this.setState({loading:true});
        _this.state.salboss==undefined?_data={name:values.CreUserName,mobile:values.Cre_tel,role:values.priseName,}:_data={name:values.CreUserName,mobile:values.Cre_tel,role:values.priseName,director_id:_this.state.salboss};
        // reqwest
        reqwest_post('/api/users',{
          access_token:localStorage['token'],user:_data
        },(data)=>{
          if(data.status=='success'){
            // window.location.hash='/app/users?current='+this.props.location.query.current;
            message.success('创建成功')
            _this.context.router.replace('/app/users?current='+this.props.location.query.current)
          }else{
            message.error(data.msg)
          }
        })
      }})
     //    reqwest({
     //      url: window.host+'/api/users',
     //      method: 'post',
     //      crossOrigin: true,
     //      type: 'json',
     //      data:{access_token:localStorage['token'],user:_data},
     //      // contentType: 'application/json',
     //      // headers:{
     //      //   'Access-Control-Allow-Origin':'*'
     //      // }
     //    }).then((data) => {
     //      console.log(data);
     //      if(data.status=='success'){
     //        // window.location.hash='/app/users?current='+this.props.location.query.current;
     //        _this.context.router.replace('/app/users?current='+this.props.location.query.current)
     //      }else{
     //        message.error(data.msg)
     //      }
     //    }).fail((err,msg)=>{
     //       message.error('无网络连接')
     //    });

     //  }else{
     //    message.error('请填必填项')
     //  }
	    // });
    this.setState({loading:false});
	}
  	// <Radio.Button value="inline">管理员</Radio.Button>
	render(){
    const {visible}=this.state;
    const { getFieldDecorator } = this.props.form;
    const nav =this.state.saler.map(function(data){
      return <Radio key={data.id} value={data.id}>{data.name}</Radio>
    })
    const _radioNode = creat_account.map((data)=>{
      return <Radio key={data.id} value={data.id}>{data.value}</Radio>
    })
    const _htmlNode = _html.map((data,index)=>{
      return <FormItem key={index} help={data.help} >
        {getFieldDecorator(data.id, data.rule)(
          <Input  prefix={data.icon} placeholder={data.label} />
        )}
      </FormItem>
    })
		return(
			<Row className={`${style.login_form}`} style={{width:'100%'}}>
        <Col   className={`${style.login_form_dec}`}>
          <h1>创建用户</h1>
          <Form hideRequiredMark={true} onSubmit={this.handleSubmit.bind(this)} >
            {_htmlNode}
            <FormItem labelCol={{span:4}} label='角色'>
              {getFieldDecorator('priseName', {
                rules: [{ required: true, message: '请输入企业名称' }],
                initialValue:'saler_director'
              })(
                <Radio.Group  onChange={this.handleRadioChange.bind(this)}>
                  {_radioNode}
	              </Radio.Group>
              )}
            </FormItem>

            <FormItem className={`${style.login_form_right}`}>
              <Button style={{width:'100%'}} loading={this.state.loading} type="primary" htmlType="submit" className="login-form-button">
                创建用户
              </Button>
            </FormItem>
          </Form>
        </Col>
        <Modal title='选择销售主管' visible={visible} onOk={this.handleOk.bind(this)}
           onCancel={()=>{this.setState({visible:false})}}
        >
          <Radio.Group onChange={(e,b)=>{this.setState({salboss:e.target.value});}}>
            {nav}
          </Radio.Group> 
        </Modal>
      </Row>
		)
	}
}
 // <FormItem help='提交表单后会使用短信告知初始密码' >
//   {getFieldDecorator('Cre_tel', {
//     initialValue:undefined,
//     rules: [{ required: true, message: '请输入正确的手机号码',validator:(rule,value,callback)=>{
//         numvail(rule,value,callback)
//     } }],
//   })(
//     <Input onChange={(e)=>{this.setState({phone:e.target.value})}} prefix={<Icon type="mobile" style={{ fontSize: 14 }} />} placeholder="手机" />
//   )}
// </FormItem>
// <FormItem >
//   {getFieldDecorator('CreUserName', {
//     rules: [{ required: true ,message:'请输入用户姓名'}],
//   })(
//     <Input onChange={(e)=>{this.setState({username:e.target.value})}} prefix={<Icon type="user" style={{ fontSize: 14 }} />} placeholder="姓名" />
//   )}
// </FormItem>
Account.contextTypes = {
  router: PropTypes.object
};
const AccountForm = Form.create()(Account);
export default connect()(AccountForm);
